package com.orangelife.mobile.lookRepair.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.common.jump.CommonJumper;
import com.common.sp.UserSp;
import com.curry.android.http.HttpUtil;
import com.curry.android.net.NetworkUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.JSONHelper;
import com.curry.android.util.PhoneCallUtil;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.app.application.ExitApplication;
import com.curry.android.adapter.FatherAdapter;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.common.view.ConfirmDialog;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.lookRepair.activity.ComplaintDeclarationActivity;
import com.orangelife.mobile.lookRepair.activity.GrapSingle2Activity;
import com.orangelife.mobile.lookRepair.activity.LookForRepairDetailActivity;
import com.orangelife.mobile.lookRepair.activity.PricingAndValuationActivity;
import com.orangelife.mobile.shoppingcart.db.ShoppingCartDao;
import com.orangelife.mobile.util.DateUtil;
import com.orangelife.mobile.util.FileHelper;
import com.orangelife.mobile.util.StringUtil;
import com.orangelife.mobile.util.ToastHelper;

import java.io.File;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LookForRepairListAdapter<T> extends FatherAdapter<T> {

	private Context context;
	private List<Map<String, Object>> list;
	private Map<String, Object> infomap;
	private LayoutInflater inflater;
	private ViewHolder holder;
	private List<Map<String, Object>> listBill;
	private String billType = "";

	private AdapterListenter adapterListener=null;

	private Dialog dialog;


	public LookForRepairListAdapter(Context context,
			List<Map<String, Object>> list) {
		this.context = context;
		this.list = list;
		inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}
	
	public void setAdapterListener(AdapterListenter adapterListener){
		this.adapterListener=adapterListener;
	}
	
	/**
	 * 下拉刷新的进度条
	 */
	private void getDataFromServer() {
		dialog = DialogHelper.getInstance().createLoadingDialog(context, Constant.LOADING);
		dialog.show();
	}


	@Override
	public int getCount() {
		if (list != null) {
			return list.size();
		} else {
			return 0;
		}
	}

	@Override
	public Object getItem(int position) {
		if (list != null) {
			return list.get(position);
		} else {
			return null;
		}
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int posiiton, View convertView, ViewGroup parent) {
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = LayoutInflater.from(context).inflate(
					R.layout.item_lookfor_repair_list, null);
			holder.llClick = (LinearLayout) convertView
					.findViewById(R.id.llClick);
			holder.tvStartWorkTime = (TextView) convertView
					.findViewById(R.id.tvStartWorkTime);
			holder.tvStatus = (TextView) convertView
					.findViewById(R.id.tvStatus);
			holder.tvContent = (TextView) convertView
					.findViewById(R.id.tvContent);
			holder.rlButton = (LinearLayout) convertView
					.findViewById(R.id.rlButton);
			holder.btnApplyForRepair = (Button) convertView
					.findViewById(R.id.btnApplyForRepair);
			holder.btnComplainRporting = (Button) convertView
					.findViewById(R.id.btnComplainRporting);
			holder.btnLookForPricing = (Button) convertView
					.findViewById(R.id.btnLookForPricing);
			holder.tvMessage = (TextView) convertView
					.findViewById(R.id.tvMessage);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		String payWay = "";
		infomap = list.get(posiiton);
		DateUtil dateUtil = new DateUtil();
		String submitTime = dateUtil.tranStringForDate_22(infomap.get("tsedit")
				.toString());
		String status = infomap.get("repaireSubStatus").toString();
		listBill = (List<Map<String, Object>>) infomap.get("billList");
		if(listBill != null && listBill.size()>0){
				billType  = listBill.get(0).get("billType").toString();
				payWay = listBill.get(0).get("payWay").toString();
		}
		String userRead = infomap.get("userReaded").toString();
		if("0".equals(userRead)){
			holder.tvMessage.setVisibility(View.VISIBLE);
		}else{
			holder.tvMessage.setVisibility(View.INVISIBLE);
		}
		 String repairMemberID = infomap.get("repairemanID").toString();
		holder.tvStartWorkTime.setText(submitTime);
		holder.tvContent.setText(infomap.get("remark").toString());
		 if(StringUtil.isBlank(repairMemberID)){
		 holder.rlButton.setVisibility(View.GONE);
		 holder.tvStatus.setText("待抢单");
		 holder.tvStatus.setTextColor(context.getResources().getColor(R.color.darkOrange));
		 }
		if ("11".equals(status)) {
			holder.rlButton.setVisibility(View.GONE);
			holder.tvStatus.setText("已取消");
			holder.tvStatus.setTextColor(context.getResources().getColor(
					R.color.lightGray));
		} else if ("1".equals(status)) {
			holder.rlButton.setVisibility(View.VISIBLE);
			holder.btnApplyForRepair.setVisibility(View.GONE);
			holder.btnComplainRporting.setVisibility(View.GONE);
			holder.btnLookForPricing.setVisibility(View.VISIBLE);
			holder.btnLookForPricing.setText("重新下单");
			holder.tvStatus.setText("待上门");
			holder.tvStatus.setTextColor(context.getResources().getColor(
					R.color.darkOrange));
		} else if ("3".equals(status) || "2".equals(status)) {
			holder.rlButton.setVisibility(View.VISIBLE);
			holder.btnApplyForRepair.setVisibility(View.GONE);
			holder.btnComplainRporting.setVisibility(View.GONE);
			holder.tvStatus.setTextColor(context.getResources().getColor(
					R.color.darkOrange));
			if ("3".equals(status)) {
				holder.tvStatus.setText("待确认估价");
				holder.btnLookForPricing.setVisibility(View.VISIBLE);
				holder.btnLookForPricing.setText("估价单");
			} else {
				holder.tvStatus.setText("待估价");
				holder.rlButton.setVisibility(View.GONE);
			}
		} else if ("6".equals(status) || "5".equals(status)) {
			holder.rlButton.setVisibility(View.VISIBLE);
			holder.btnApplyForRepair.setVisibility(View.GONE);
			holder.btnComplainRporting.setVisibility(View.GONE);
			holder.btnLookForPricing.setVisibility(View.VISIBLE);
			holder.tvStatus.setTextColor(context.getResources().getColor(
					R.color.darkOrange));
			if ("6".equals(status)) {
				holder.tvStatus.setText("待确认定价");
				holder.btnLookForPricing.setText("定价单");
			} else {
				holder.tvStatus.setText("待定价");
				if("2".equals(billType)){
					holder.btnLookForPricing.setText("定价单");
				}else{
					holder.btnLookForPricing.setText("估价单");
				}
			}
		} else if ("4".equals(status)) {
			holder.tvStatus.setText("跟进中");
			holder.tvStatus.setTextColor(context.getResources().getColor(
					R.color.darkOrange));
			holder.rlButton.setVisibility(View.VISIBLE);
			holder.btnApplyForRepair.setVisibility(View.GONE);
			holder.btnComplainRporting.setVisibility(View.GONE);
			holder.btnLookForPricing.setVisibility(View.VISIBLE);
			holder.btnLookForPricing.setText("估价单");
		} else if ("10".equals(status)) {
			holder.tvStatus.setText("已结单");
			holder.tvStatus.setTextColor(context.getResources().getColor(
					R.color.lightGray));
			holder.btnApplyForRepair.setVisibility(View.GONE);
			if(holder.btnLookForPricing.getText().equals("重新下单")){
				holder.btnLookForPricing.setVisibility(View.GONE);
			}
			holder.rlButton.setVisibility(View.VISIBLE);
			listBill = (List<Map<String, Object>>) list.get(posiiton).get(
					"billList");
			if ("0".equals(payWay)) {
				holder.rlButton.setVisibility(View.GONE);
			} else if("1".equals(payWay)){
				holder.btnApplyForRepair.setVisibility(View.VISIBLE);
				holder.btnComplainRporting.setVisibility(View.VISIBLE);
				holder.btnLookForPricing.setVisibility(View.GONE);
				holder.btnLookForPricing.setText("定价单");
				holder.btnComplainRporting.setText("投诉申报");
			}
		} else if ("9".equals(status) || "8".equals(status)) {
			holder.rlButton.setVisibility(View.VISIBLE);
			holder.btnApplyForRepair.setVisibility(View.VISIBLE);
			holder.btnComplainRporting.setVisibility(View.VISIBLE);
			holder.btnLookForPricing.setVisibility(View.GONE);
			holder.btnLookForPricing.setText("定价单");
			holder.btnApplyForRepair.setText("申请保修");
			holder.btnComplainRporting.setText("投诉申报");
			holder.btnApplyForRepair.setTextColor(context.getResources()
					.getColor(R.color.darkOrange));
			holder.btnApplyForRepair
					.setBackgroundResource(R.drawable.shape_edit_orange);
			if ("9".equals(status)) {
				holder.tvStatus.setText("待保修");
				holder.tvStatus.setTextColor(context.getResources().getColor(R.color.darkOrange));
			} else {
				holder.tvStatus.setText("已验收");
				holder.tvStatus.setTextColor(context.getResources().getColor(R.color.darkOrange));
			}
		} else if ("7".equals(status)) {
			holder.tvStatus.setText("待取消订单");
			holder.rlButton.setVisibility(View.VISIBLE);
			holder.btnApplyForRepair.setText("待取消订单");
			holder.btnApplyForRepair.setVisibility(View.GONE);
			holder.btnComplainRporting.setVisibility(View.VISIBLE);
			holder.btnComplainRporting.setText("恢复订单");
			holder.btnLookForPricing.setVisibility(View.VISIBLE);
			listBill = (List<Map<String, Object>>) list.get(posiiton).get(
					"billList");
			holder.btnLookForPricing.setText("估价单");
			

		}
		
		holder.llClick.setOnClickListener(new listener(infomap));
		holder.btnApplyForRepair.setOnClickListener(new listener(infomap));
		holder.btnComplainRporting.setOnClickListener(new listener(infomap));
		holder.btnLookForPricing.setOnClickListener(new listener(infomap));

		return convertView;
	}

	class listener implements View.OnClickListener {

		private Map<String, Object> map = null;

		public listener(Map<String, Object> map) {
			this.map = map;
		}

		@Override
		public void onClick(View view) {
			String stat = map.get("repaireSubStatus").toString();
			String invcRepaireID = map.get("invcRepaireID").toString();
			 Intent intent = new Intent();
			switch (view.getId()) {
			case R.id.llClick:
				if (!NetworkUtil.isConnectedNet(context)) {
					Toast.makeText(
							context,
							context.getResources().getString(
									R.string.net_disconnected),
							Toast.LENGTH_SHORT).show();
					return;
				}
				String repairMemberID = map.get("repairemanID").toString();
				String invoiceID = map.get("repaireID").toString();
				if(StringUtil.isBlank(repairMemberID)){
					ExitApplication.getInstance().addPaidActivity((Activity)context);
					intent = new Intent();
					intent.putExtra("followID", invoiceID);
					intent.setClass(context, GrapSingle2Activity.class);
					context.startActivity(intent);
				}else{
					intent = new Intent();
					Bundle bundle = new Bundle();
					bundle.putSerializable("detail", (Serializable) map);
					intent.setClass(context, LookForRepairDetailActivity.class);
					intent.putExtras(bundle);
					context.startActivity(intent);
				}
				break;
			case R.id.ibCall:
				String phone = map.get("linkmanTel").toString();
				// String name = infomap.get("merchantName").toString();
				// String time = TimeUtil.timeStampToDate(String.valueOf(System
				// .currentTimeMillis()));
				// String url = infomap.get("merchantLogo").toString();
				// Map<String, String> map = new LinkedHashMap<String,
				// String>();
				// map.put("name", name);
				// map.put("phone", phone);
				// map.put("time", time);
				// saveFile(map);
				
				PhoneCallUtil.getInstances().PhoneCall(context, phone);
				break;
			case R.id.btnApplyForRepair:
				getDataFromServer();
				sendComplaintDeclaration(map.get("invcRepaireID").toString());
				break;
			case R.id.btnComplainRporting:
				if ("8".equals(stat)||"9".equals(stat)||"10".equals(stat)) {
					Intent intentCD = new Intent();
					intentCD.putExtra("repairID", map.get("invcRepaireID")
							.toString());
					intentCD.putExtra("invcID", map.get("invcID").toString());
					// intentCD.putExtra("linkmanTel",
					// infomap.get("linkmanTel").toString());
					intentCD.setClass(context,
							ComplaintDeclarationActivity.class);
					context.startActivity(intentCD);
				} else if ("7".equals(stat)) {
					// 撤销取消订单
					String invcID = map.get("invcRepaireID").toString();
					getDataFromServer();
					cancelTheOrder(invcID);
				}

				break;
			case R.id.btnLookForPricing:
				intent = new Intent();
				intent.putExtra("invcRepaireID", invcRepaireID);
				intent.putExtra("invcID", infomap.get("invcID").toString());
				if ("1".equals(stat)) {
					isOrderDialog(invcRepaireID);
				} else if ("3".equals(stat) || "4".equals(stat) || "5".equals(stat)) {
					if("5".equals(stat)){
						intent.putExtra("VP", 1);
						intent.putExtra("isNeed", 1);
					}else{
						intent.putExtra("VP", 0);
						intent.putExtra("isNeed", 0);
					}
					intent.setClass(context, PricingAndValuationActivity.class);
					context.startActivity(intent);
				} else if("2".equals(stat)){
				} else if ("6".equals(stat) || "8".equals(stat) || "9".equals(stat) || "10".equals(stat) ) {
					intent.putExtra("VP", 1);
					intent.putExtra("isNeed", 1);
					intent.setClass(context, PricingAndValuationActivity.class);
					context.startActivity(intent);
				}else  if("7".equals(stat) || "11".equals(stat)){
						intent.putExtra("VP", 0);
						intent.putExtra("isNeed", 0);
						intent.setClass(context, PricingAndValuationActivity.class);
						context.startActivity(intent);
				}
				break;

			default:
				break;
			}

		}
	}

	/**
	 * 弹出对话框
	 */
	private void isOrderDialog(final String repairID) {
		final ConfirmDialog dialog = new ConfirmDialog(context, "温馨提示",context.getResources().getString(R.string.order_again), "取消", "重新下单");
		dialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
			@Override
			public void doLeft() {
				dialog.dismiss();
			}
			@Override
			public void doRight() {
				dialog.dismiss();
				// 重新下单
				reOrder(repairID);
				return;
			}
		});
		dialog.show();
	}

	private void isOrderDialog1(final String repairID) {
		AlertDialog.Builder builder = new Builder(context);
		builder.setMessage(R.string.order_again);
		builder.setPositiveButton("重新下单",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						// 重新下单
						reOrder(repairID);
						return;
					}
				});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.create().show();
	}

	/**
	 * 储存通话记录
	 * 
	 * @param map
	 */
	@SuppressWarnings({ "static-access", "rawtypes" })
	private void saveFile(Map map) {
		String filename = UserSp.getRegPhone();
		FileHelper file = new FileHelper(context, filename + ".txt");
		file.saveFile(map, context.MODE_APPEND);
		boolean hadCall = true;
	}

	/**
	 * 提交申请保修
	 */
	private void sendComplaintDeclaration(String repairID) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("invcRepaireID", repairID);
		Map<String, Object> rootMap = new HashMap<String, Object>();
		rootMap.put("map", map);
		rootMap.put("url", Constant.URL_APPLY_GUARANTEE);
		rootMap.put("wat", 1);
		new JSONRequest(JSONRequest.PUT, rootMap, handler, HttpUtil.ACTION_JSON);
	}
	/**
	 * 撤销取消订单
	 */
	private void cancelTheOrder(String repairID) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("invcRepaireID", repairID);
		Map<String, Object> rootMap = new HashMap<String, Object>();
		rootMap.put("map", map);
		rootMap.put("url", Constant.URL_CANCEL_THE_ORDER);
		rootMap.put("wat", 3);
		new JSONRequest(JSONRequest.PUT, rootMap, handler, HttpUtil.ACTION_JSON);
	}

	/**
	 * 重新下单
	 */
	private void reOrder(String repairID){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("invcRepaireID", repairID);
		JSONRequest.getInstance().sendRequest(JSONRequest.PUT,Constant.URL_RE_ORDER, map, handler,4,HttpUtil.ACTION_JSON);
	}
	public interface AdapterListenter{
		public void refresh(String str);
	}
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				DialogHelper.closeDialog(dialog);
				String errInfo = JSONHelper.jsonToMap(msg.obj.toString())
						.get("errInfo").toString();
				if (errInfo.equals("OK")) {
					ToastHelper.getInstance()._toast("申请成功，请耐心等待");
					if(adapterListener!=null){
						adapterListener.refresh(msg.obj.toString());
					}
				} else {
					ToastHelper.getInstance()._toast("申请失败");
				} 
				break;
			case 3:
				DialogHelper.closeDialog(dialog);
				errInfo = JSONHelper.jsonToMap(msg.obj.toString())
				.get("errInfo").toString();
				if (errInfo.equals("OK")) {
					ToastHelper.getInstance()._toast("撤销成功");
					if(adapterListener!=null){
						adapterListener.refresh(msg.obj.toString());
					}
				} else {
					ToastHelper.getInstance()._toast("撤销失败");

				}
				break;
			case 4:
				DialogHelper.closeDialog(dialog);
				errInfo = JSONHelper.jsonToMap(msg.obj.toString())
				.get("errInfo").toString();
				if (errInfo.equals("OK")) {
					ToastHelper.getInstance()._toast("下单成功");
					if(adapterListener!=null){
						adapterListener.refresh(msg.obj.toString());
					}
				} else {
					ToastHelper.getInstance()._toast("下单失败");

				}
				break;
 
			case 1011:
				CommonJumper.jumpToLogin(context);
				break;
			case 500:
				DialogHelper.closeDialog(dialog);
				ToastHelper.getInstance()._toast(
						msg.obj.toString());
				break;

			default:
				break;
			}
		}

	};

	class ViewHolder {
		/** 提交时间 */
		private TextView tvStartWorkTime;
		/** 提交内容 */
		private TextView tvContent;
		/** 状态 */
		private TextView tvStatus;
		/** 放按钮的linearlayout */
		private LinearLayout rlButton;
		/** 投诉申报按钮 */
		private Button btnComplainRporting;
		/** 申请报修按钮 */
		private Button btnApplyForRepair;
		/** 查看定价单按钮 */
		private Button btnLookForPricing;
		/** 详情点击 */
		private LinearLayout llClick;
		/** 提示消息 */
		private TextView tvMessage;
	}

	@Override
	public BaseAdapter setList(List<T> list) {
		this.list = (List<Map<String, Object>>) list;
		return LookForRepairListAdapter.this;
	}

}
